package com.zjpavt.client.udp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 发送tcp数据包
 * @author zyc
 */
@Slf4j
public class TcpSender {

    /**
     * 发送TCP数据到指定设备
     * @param hostName
     * @param port
     * @param bytes
     * @return
     */
    public static boolean sendTcpPacket(String hostName, int port, byte[] bytes) {
        try {
            Socket client = new Socket(hostName, port);
            client.setSoTimeout(10000);
            //获取Socket的输出流，用来发送数据到服务端
            PrintStream out = new PrintStream(client.getOutputStream());
            out.write(bytes);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(client != null) {
                //如果构造函数建立起了连接，则关闭套接字，如果没有建立起连接，自然不用关闭
                client.close(); //只关闭socket，其关联的输入输出流也会被关闭
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        byte[] bytesOn = {0x6f, 0x70, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x2e, 0x6f, 0x6e, 0x0d};
        String x = new String(bytesOn);
        System.out.println(x);
//        System.out.println(String.valueOf(bytesOn).toString());
//        TcpSender.sendTcpPacket("192.168.199.137", 10000, bytesOn);
        byte[] bytesOff = {0x6f, 0x70, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x2e, 0x6f, 0x66, 0x66, 0x0d};
        String x1 = new String(bytesOff);
        System.out.println(x1);
//        TcpSender.sendTcpPacket("192.168.28.34", 10000, bytesOff);
    }
}
